package site.yaoer.dongbao.portal.web.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import site.yaoer.dongbao.ums.common.base.annotations.TokenCheck;
import site.yaoer.dongbao.ums.utils.JwtUtils;

import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器进入");
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            throw new LoginException("Token 为空！");
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        if (method.isAnnotationPresent(TokenCheck.class)) {
            TokenCheck annotation = method.getAnnotation(TokenCheck.class);
            if (annotation.required()) {
                try {
                    JwtUtils.parseToken(token);
                }catch (Exception e) {
                    throw new LoginException("Token 异常！");
                }
            }
        }

        return true;
    }
}
